package org.mytools.dao;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class DaoGenerator {

	private VelocityEngine velocityEngine;

	public DaoGenerator() {
		initialize();
	}

	private void initialize() {
		Properties props = new Properties();
		props.setProperty("resource.loader", "class");
		props.setProperty("class.resource.loader.class",
				"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		VelocityEngine ve = new VelocityEngine();
		ve.init(props);
		this.velocityEngine = ve;
	}

	private Template getTemplate(String name) {
		return this.velocityEngine.getTemplate(name);
	}

	public void generate(VelocityContext context, String templateName, File file) {
		try {
			OutputStreamWriter writer;
			writer = new OutputStreamWriter(new FileOutputStream(file));
			getTemplate(templateName).merge(context, writer);

			writer.flush();
			writer.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

}
